package com.homedo.microservice.wechat.personal.secretary.entity;

import com.homedo.microservice.wechat.personal.secretary.service.PersonalBotService;
import io.github.biezhi.wechat.WeChatBot;
import io.github.biezhi.wechat.api.annotation.Bind;
import io.github.biezhi.wechat.api.constant.Config;
import io.github.biezhi.wechat.api.enums.AccountType;
import io.github.biezhi.wechat.api.enums.MsgType;
import io.github.biezhi.wechat.api.model.Account;
import io.github.biezhi.wechat.api.model.WeChatMessage;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class PersonalBot extends WeChatBot {
    @Setter
    private PersonalBotBiz botBiz;

    private static final Logger _LOGGER = LoggerFactory.getLogger(PersonalBot.class);

    public PersonalBot(Config config) {
        super(config);
    }

    //TODO 修改成根据账户走的
    List<String> keywords = new ArrayList<>();

    {
        keywords.add("在不在");
        keywords.add("在吗");
        keywords.add("在么");
        keywords.add("怎么卖");
        keywords.add("多少钱");
        keywords.add("产品");
        keywords.add("你好");
    }

    @Bind(msgType = MsgType.TEXT, accountType = AccountType.TYPE_FRIEND)
    public void handleFriendText(WeChatMessage message) {
        boolean isSelfSend = this.checkSelfSend(message);

        if (!isSelfSend && StringUtils.isNotEmpty(message.getName())) {//不是自己发的消息 并且发送方有名称（备注或昵称）即来自好友的消息
            _LOGGER.info("接收到 [{}] 的消息: {}", message.getName(), message.getText());

            String msg = message.getText();
            boolean contain = false;
            for (String keyword : keywords) {
                contain = msg.contains(keyword);
                if (contain) {
                    break;
                }
            }

            if (contain) {
                String replyMsg = "****" + new DateTime().toString("yyyyMMdd HH:mm:ss") + "（" + message.getName() + "）说：“" + msg + "”";
                this.sendMsgToFileHelper(replyMsg);
//                this.sendMsg(message.getFromUserName(), "自动回复: " + message.getText());
            }

        }

        if (isSelfSend && "filehelper".equals(message.getToUserName())) {//是自己发送的 并且接收方是文件传输助手
            String receiveMsg = message.getText().trim();

            if ("帮助".equals(receiveMsg)) {
                String replyMsg = "未办理业务或重试";
                if (botBiz != null) {
                    replyMsg = botBiz.getReplyBizMsg();
                }
                this.sendMsgToFileHelper(replyMsg);
            } else {
                if (botBiz != null) {
                    botBiz.dealBiz(receiveMsg);
                }
            }

        }
    }

    private boolean checkSelfSend(WeChatMessage message) {
        return this.session().getUserName().equals(message.getFromUserName());
    }

//    @Bind(msgType = MsgType.TEXT, accountType = AccountType.TYPE_SPECIAL)
//    public void handleFilehelperText(WeChatMessage message) {
//        if ("filehelper".equals(message.getFromUserName())) {
//            _LOGGER.info("接收到 [文件传输助手] 的消息: {},{},{}", message.getFromUserName(), message.getName(), message.getText());
//            this.sendMsg(message.getFromUserName(), "自动回复: " + message.getText());
//        }
//    }

    @Override
    protected void other() {
        _LOGGER.info("[登录成功之后开始加载用户业务...]");
        if (botBiz != null) {
            botBiz.loadBizs();
        }

        this.sendMsgToFileHelper("恭喜你，登录成功！\n可以输入“帮助”，查看可以使用的功能");
    }


    static PersonalBotService personalBotService = new PersonalBotService();

    public static void main(String[] args) {
        String sysLoginAccount = "13636621498";
        PersonalBot personalBot = new PersonalBot(Config.me().autoLogin(false).showTerminal(false).filePrefix(sysLoginAccount + "_").sysLoginAccount(sysLoginAccount));
        personalBot.setBotBiz(new PersonalBotBiz(personalBot, personalBotService));

        personalBot.start();
        Timer timer = new Timer("test-timer", true);
        timer.schedule(new TimerTask() {
            int retry = 0;

            @Override
            public void run() {
                try {
                    personalBot.api().getLoginQrImage();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (++retry == 1) {
                    _LOGGER.info("停止拉取数据");
                    timer.cancel();
//                    personalBot.stop();
                }
            }
        }, 0, 30000);


        while (true) {
            Account account = personalBot.api().getAccountByName("一片叶子");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}